package com.yc.qunxing.web;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yc.qunxing.entity.DriverLocations;
import com.yc.qunxing.entity.DriverVehicles;
import com.yc.qunxing.entity.Drivers;
import com.yc.qunxing.entity.Users;
import com.yc.qunxing.properties.JwtProperties;
import com.yc.qunxing.result.Result;
import com.yc.qunxing.service.IDriverLocationsService;
import com.yc.qunxing.service.IDriverVehiclesService;
import com.yc.qunxing.service.IDriversService;
import com.yc.qunxing.utils.AppJwtUtil;
import com.yc.qunxing.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 鹏哥
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/drivers")
@Slf4j
public class DriverController {


    @Autowired
    private IDriversService iDriversService;
    @Autowired
    private IDriverLocationsService iDriverLocationsService;
    @Autowired
    private IDriverVehiclesService iDriverVehiclesService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result<Drivers> LoginedDriver(HttpServletRequest req, HttpServletResponse resp,@RequestBody Drivers drivers) throws IOException {
        // 从请求体中获取手机号和密码
        String phoneNumber =drivers.getPhoneNumber();
        String password = drivers.getPassword();
        String verification = drivers.getVerification();
        int t=doPics(req,resp,verification);
        if(t==0){
            return Result.error("验证码错误");
        }
        // 构建查询条件
        QueryWrapper<Drivers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number", phoneNumber).eq("password", password).in("status", 1, 2, 3);

        // 根据手机号和密码查询用户信息
        Drivers driver = iDriversService.getOne(queryWrapper);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("driverId", driver.getId());
        String token = JwtUtil.createJWT(
                JwtProperties.adminSecretKey,
                JwtProperties.adminTtl,
                claims);
/*        String token = AppJwtUtil.getToken(driver.getId().longValue());*/
        driver.setToken(token);
        if (driver != null) {
            // 登录成功
            return Result.success(driver);
        } else {
            // 登录失败
            return Result.error("手机号或密码错误");
        }
    }
    @PostMapping("/register")
    public Result<String> RegisterUser(HttpServletRequest req, HttpServletResponse resp,@RequestBody Drivers drivers) throws IOException {
        String verification = drivers.getVerification();
        int t=doPics(req,resp,verification);
        if(t==0){
            return Result.error("验证码错误");
        }
        return iDriversService.registerDriver(drivers);
    }
    @PutMapping("/exitStatus")
    public Result<String> ExitStatus(@RequestParam Integer driverId){
        Drivers drivers=new Drivers();
        drivers.setId(driverId);
        drivers.setStatus("3");
        iDriversService.updateById(drivers);
        return Result.success();
    }
    @PutMapping("/updateDriverStatus")
    public Result<String> UpdateDriverStatus(@RequestBody Drivers drivers){
        iDriversService.updateById(drivers);
        return Result.success();
    }
    @GetMapping("/getLocation")
    public Result<String> GetLocation(@RequestParam Integer driverId){
        DriverLocations byId = iDriverLocationsService.getById(driverId);
        String locaton1= byId.getLocation();
        return Result.success(locaton1);
    }
    @GetMapping("/getById")
    public Result<Drivers> GetById(@RequestParam Integer driverId){
        Drivers byId = iDriversService.getById(driverId);
        return Result.success(byId);
    }
    @GetMapping("/getVerById")
    public Result<DriverVehicles> GetVerById(@RequestParam Integer driverId){
        DriverVehicles byId = iDriverVehiclesService.getById(driverId);
        return Result.success(byId);
    }

    @PostMapping("/changePassword")
    public Result<Map<String, Object>> changePassword(@RequestBody Map<String, Object> request) {
        Integer driverId = (Integer) request.get("driverId");
        String originalPassword = (String) request.get("originalPassword");
        String newPassword = (String) request.get("newPassword");

        Map<String, Object> response = new HashMap<>();
        if (iDriversService.verifyOriginalPassword(driverId, originalPassword)) {
            iDriversService.changePassword(driverId, newPassword);
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }
    @PostMapping("/changePhone")
    public Result<Map<String, Object>> changePhone(@RequestBody Map<String, Object> request) {
        Integer driverId = (Integer) request.get("driverId");
        String phone = (String) request.get("phone");

        Map<String, Object> response = new HashMap<>();
        if (iDriversService.changePhone(driverId, phone)) {
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }
    @PostMapping("/changeName")
    public Result<Map<String, Object>> changeName(@RequestBody Map<String, Object> request) {
        Integer driverId = (Integer) request.get("driverId");
        String name = (String) request.get("userName");

        Map<String, Object> response = new HashMap<>();
        if (iDriversService.changeName(driverId, name)) {
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }
    @PostMapping("/sendVerificationCode")
    public Result<Map<String, Object>> sendVerificationCode(@RequestBody Map<String, Object> request) {
        Integer driverId = (Integer) request.get("driverId");
        String email = (String) request.get("email");
        String code = (String) request.get("code");

        Map<String, Object> response = new HashMap<>();
        if (iDriversService.sendVerificationCode(driverId, email, code)) {
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }

    @PostMapping("/changeEmail")
    public Result<Map<String, Object>> changeEmail(@RequestBody Map<String, Object> request) {
        Integer driverId = (Integer) request.get("driverId");
        String newEmail = (String) request.get("newEmail");

        Map<String, Object> response = new HashMap<>();
        if (iDriversService.changeEmail(driverId, newEmail)) {
            response.put("code", 1);
        } else {
            response.put("code", 0);
        }
        return Result.success(response);
    }
    @GetMapping("/getDriverByManager")
    public Result<PageInfo<Drivers>> GetDriverByManager( @RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "10") Integer size,
                                              @RequestParam(required = false) String keyword,
                                              @RequestParam(required = false) String keywordOrder,
                                              @RequestParam(required = false) String searchVehicle){
        PageHelper.startPage(page, size);
        List<Drivers> driversList = iDriversService.getDriverByManager(keyword,keywordOrder,searchVehicle);
        PageInfo<Drivers> pageInfo = new PageInfo<>(driversList);
        return Result.success(pageInfo);
    }
    protected int doPics(HttpServletRequest req, HttpServletResponse resp, String usafe) throws IOException {
        HttpSession session=req.getSession();
        String sessionId = session.getId();
        /*String scpat = (String) session.getAttribute("verityCode");*/
        String scpat = (String) redisTemplate.opsForValue().get(sessionId);
        System.out.println("who:"+usafe+","+scpat);
        if(scpat != null && scpat.equals(usafe)){
            return 1;
        }else{
            return 0;
        }
    }
}
